import axios from 'axios'
import { isObject } from '@/utils/type-judge'
import Vue from 'vue'

// axios默认配置
const AXIOS_DEFAULT_CONFIG = {
  timeout: 15000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
}
let options = {}

// 请求成功
function requestSuccess (req) {
  req.data = {
    system: options.system || {},
    data: req.data || {}
  }
  return req
}
// 请求失败
function requestFail (error) {
  Vue.$message.error(`${error.message}(${error.config.url})`)
  return Promise.reject(error)
}

// 响应成功
function responseSuccess (response) {
  let { data: res } = response
  const system = res.system || {}
  // 网关获取uid  自动添加到$user
  if (res.data && isObject(res.data.result_rows) && !res.data.result_rows.uid) { res.data.result_rows.uid = system.uid; Vue.prototype.$user.uid = system.uid }
  // 未登录或登录已过期则跳到登录页
  if (res.result === 10200007 || res.result === 10200005) {
    window.location.href = `//passport.fenqile.com?url=${encodeURIComponent(window.location.href)}`
    return
  }

  if (res.result === 0 && res.data) {
    res = res.data
    if (res.result === 0 || res.result === '0') {
      return res.result_rows
    } else {
      console.log('responseSuccess response: ', response)
      console.log('responseSuccess res: ', res)
    }
  }
  return Promise.reject(res)
}
// 响应失败
function responseFail (error) {
  Vue.$message.error(`${error.message} in '${error.config.url}'`)
  return Promise.reject(error)
}

// 注入请求和响应拦截
const axiosInstance = axios.create(AXIOS_DEFAULT_CONFIG)
axiosInstance.interceptors.request.use(requestSuccess, requestFail)
axiosInstance.interceptors.response.use(responseSuccess, responseFail)

export default (opt = {}) => {
  options = opt
  return axiosInstance
}
